﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Casamiel.API.Infrastructure;
using Casamiel.API.Infrastructure.Filters;
using Casamiel.Domain.Response;
using Casamiel.Domain.Response.Account;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using MediatR;
using Casamiel.Application.Commands;
using Casamiel.Domain.Request;
using Casamiel.API.Application;
using NLog;
using Newtonsoft.Json;
// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace Casamiel.API.Controllers.V2
{
    /// <summary>
    /// 
    /// </summary>
    [ApiVersion("2.0")]
    [Produces("application/json")]
    [Route("api/v{api-version:apiVersion}/[controller]")]
#if !DEBUG

    [Authorize]
    [TypeFilterAttribute(typeof(CheckLoginAttribute))]
       
#endif
    [ApiController]
    public class AccountController : BaseController
    {
        private readonly NLog.ILogger logger = LogManager.GetLogger("BizInfo");

        private readonly IServiceScopeFactory _scopeFactory;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="serviceScopeFactory"></param>
        public AccountController(IServiceScopeFactory serviceScopeFactory)
        {
            _scopeFactory = serviceScopeFactory;
        }

        /// <summary>
        /// 检测信息是否完整
        /// </summary>
        /// <param name="token"></param>
        /// <returns>true 完整</returns>
        [HttpPost]
        [Route("[Action]")]
        public async Task<BaseResult<bool>> IsMemberInfoComplete([FromHeader(Name = "u-token")] string token)
        {
            using var scope = _scopeFactory.CreateScope();
            var _mediator = scope.ServiceProvider.GetRequiredService<IMediator>();
            var mobile = MemberHelper.GetMobile(token);
            //var member = await _memberRepository.FindAsync<ICasaMielSession>(mobile).ConfigureAwait(false);
            //var data = new { Mobile = member.Mobile, Nick = member.Nick, Birthday = member.Birthday, Sex = member.Sex, TrueName = member.TrueName, Email = member.Email, member.InvitationCode };
            //var a = new { code = 0, data = data };
            //return new JsonResult(a);
            var cmd = new IsMemberInfoCompleteCommand {
                Mobile = mobile
            };
            var result = await _mediator.Send(cmd).ConfigureAwait(false);
            return result;
        }

        /// <summary>
        /// 保存用户信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("[Action]")]
        public async Task<BaseResult<string>> SaveMemberInfo(MemberSaveCardRequest request, [FromHeader(Name = "u-token")] string token)
        {
            if (request is null) {
                throw new ArgumentNullException(nameof(request));
            }
			logger.Trace($"SaveMemberInfo:{JsonConvert.SerializeObject(request)}");
            using var scope = _scopeFactory.CreateScope();
            var _mediator = scope.ServiceProvider.GetRequiredService<IMediator>();
            var _storeApiService = scope.ServiceProvider.GetRequiredService<IStoreApiService>();

            var mobile = MemberHelper.GetMobile(token);
            var cmd = new MemberExtInfoCommand {
                Mobile = mobile,
                City = request.City,
                Provice = request.Provice,
                Sex = request.Sex,
                IsAddWeixin = request.IsAddWeixin,
                StoreName = request.StoreName,
                District = request.District,
                LiveWay = request.LiveWay,
                RealName = request.RealName,
                StoreDistance = request.StoreDistance,
                InvitationCode = request.InvitationCode
            };
			if (request.StoreId.HasValue) {
                cmd.StoreId = request.StoreId;
			}

            if (request.Birthday.HasValue) {
                cmd.Birthday = request.Birthday.Value;
            }


            var result = await _mediator.Send(cmd).ConfigureAwait(false);
            if (!string.IsNullOrEmpty(request.InvitationCode) && result.Code == 0) {
                try {
                    await _storeApiService.AddReferral(mobile, request.InvitationCode).ConfigureAwait(false);
                } catch (Exception ex) {
                    logger.Error($"AddReferral:{ex.StackTrace}");
                }

            }
            return result;
        }
        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        /// <remarks>
        /// </remarks>
        [HttpPost]
        [Route("[Action]")]
        public async Task<BaseResult<MemberInfoResponse>> GetMemberInfo([FromHeader(Name = "u-token")] string token)
        {
            using var scope = _scopeFactory.CreateScope();
            var _mediator = scope.ServiceProvider.GetRequiredService<IMediator>();
            var mobile = MemberHelper.GetMobile(token);

            var cmd = new GetMemberInfoCommand(mobile);
            var result = await _mediator.Send(cmd).ConfigureAwait(false);
            return result;
        }

    }
}
